<template>
  <div class="shop-management">
    <!-- 页面头部导航 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="primary" 
          icon="ArrowLeft" 
          @click="$router.back()"
          class="back-btn"
        >
          返回
        </el-button>
        <div class="page-info">
          <h2>店铺管理</h2>
          <p>管理系统中所有店铺的基础信息</p>
        </div>
      </div>
      
      <div class="header-right">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="navigateToHome" class="breadcrumb-link">控制台</el-breadcrumb-item>
          <el-breadcrumb-item>店铺管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <el-button 
        type="primary" 
        icon="Plus" 
        @click="showCreateDialog = true"
      >
        新建店铺
      </el-button>
      
      <div class="toolbar-right">
        <el-select 
          v-model="statusFilter" 
          placeholder="按状态筛选" 
          clearable
          @change="handleStatusFilter"
        >
          <el-option label="运营中" value="active" />
          <el-option label="已暂停" value="suspended" />
          <el-option label="已关闭" value="closed" />
        </el-select>
        
        <el-button 
          icon="Refresh" 
          @click="loadShops"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 店铺列表表格 -->
    <el-table 
      :data="shopsData" 
      v-loading="loading"
      stripe
      border
      style="width: 100%"
    >
      <el-table-column prop="code" label="店铺编号" width="120" />
      <el-table-column prop="name" label="店铺名称" min-width="180" />
      <el-table-column prop="description" label="店铺描述" min-width="200" show-overflow-tooltip />
      <el-table-column prop="contactPhone" label="联系电话" width="140" />
      <el-table-column prop="status" label="运营状态" width="100">
        <template #default="{ row }">
          <el-tag 
            :type="getStatusType(row.status)"
            size="small"
          >
            {{ row.statusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdByName" label="创建人" width="120" />
      <el-table-column prop="createdAt" label="创建时间" width="160">
        <template #default="{ row }">
          {{ formatTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            text
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          
          <el-dropdown @command="(command) => handleStatusChange(row, command)">
            <el-button type="warning" size="small" text>
              状态 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  command="active" 
                  :disabled="row.status === 'active'"
                >
                  启用
                </el-dropdown-item>
                <el-dropdown-item 
                  command="suspended" 
                  :disabled="row.status === 'suspended'"
                >
                  暂停
                </el-dropdown-item>
                <el-dropdown-item 
                  command="closed" 
                  :disabled="row.status === 'closed'"
                >
                  关闭
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <el-button 
            type="danger" 
            size="small" 
            text
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建店铺对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建新店铺" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="createFormRef" 
        :model="createForm" 
        :rules="createRules" 
        label-width="100px"
      >
        <el-form-item label="店铺名称" prop="name">
          <el-input 
            v-model="createForm.name" 
            placeholder="请输入店铺名称（2-100字符）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="店铺编号" prop="code">
          <el-input 
            v-model="createForm.code" 
            placeholder="请输入店铺编号（3-50字符，仅大写字母和数字）"
            maxlength="50"
            show-word-limit
            @blur="checkShopCode"
          />
          <div class="form-tip">编号用于系统内部识别，创建后不可修改</div>
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input 
            v-model="createForm.contactPhone" 
            placeholder="请输入联系电话"
            maxlength="20"
          />
        </el-form-item>
        
        <el-form-item label="店铺描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入店铺描述（最大500字符）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreate"
          :loading="createLoading"
        >
          创建店铺
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑店铺对话框 -->
    <el-dialog 
      v-model="showEditDialog" 
      title="编辑店铺信息" 
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="editFormRef" 
        :model="editForm" 
        :rules="editRules" 
        label-width="100px"
      >
        <el-form-item label="店铺编号">
          <el-input :value="currentShop?.code" disabled />
          <div class="form-tip">店铺编号不可修改</div>
        </el-form-item>
        
        <el-form-item label="店铺名称" prop="name">
          <el-input 
            v-model="editForm.name" 
            placeholder="请输入店铺名称（2-100字符）"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input 
            v-model="editForm.contactPhone" 
            placeholder="请输入联系电话"
            maxlength="20"
          />
        </el-form-item>
        
        <el-form-item label="店铺描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入店铺描述（最大500字符）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleUpdate"
          :loading="updateLoading"
        >
          保存修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElForm, ElTable } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { adminShopApi, type Shop, type CreateShopParams, type UpdateShopParams } from '@renderer/api/admin'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const createLoading = ref(false)
const updateLoading = ref(false)
const shopsData = ref<Shop[]>([])
const statusFilter = ref<string>('')

// 对话框显示状态
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const currentShop = ref<Shop | null>(null)

// 表单引用
const createFormRef = ref<InstanceType<typeof ElForm>>()
const editFormRef = ref<InstanceType<typeof ElForm>>()

// 创建表单
const createForm = reactive<CreateShopParams>({
  name: '',
  code: '',
  description: '',
  contactPhone: ''
})

// 编辑表单
const editForm = reactive<UpdateShopParams>({
  id: 0,
  name: '',
  description: '',
  contactPhone: ''
})

// 表单验证规则
const createRules = {
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 100, message: '店铺名称长度应为2-100字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入店铺编号', trigger: 'blur' },
    { min: 3, max: 50, message: '店铺编号长度应为3-50字符', trigger: 'blur' },
    { pattern: /^[A-Z0-9]+$/, message: '店铺编号只能包含大写字母和数字', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const editRules = {
  name: [
    { min: 2, max: 100, message: '店铺名称长度应为2-100字符', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 加载店铺列表
const loadShops = async () => {
  try {
    loading.value = true
    const response = await adminShopApi.getShops()
    shopsData.value = response.data.data
  } catch (error) {
    console.error('加载店铺列表失败:', error)
    ElMessage.error('加载店铺列表失败')
  } finally {
    loading.value = false
  }
}

// 按状态筛选
const handleStatusFilter = async () => {
  if (!statusFilter.value) {
    await loadShops()
    return
  }
  
  try {
    loading.value = true
    const response = await adminShopApi.getShopsByStatus(statusFilter.value as any)
    shopsData.value = response.data.data
  } catch (error) {
    console.error('按状态筛选失败:', error)
    ElMessage.error('筛选失败')
  } finally {
    loading.value = false
  }
}

// 检查店铺编号
const checkShopCode = async () => {
  if (!createForm.code) return
  
  try {
    const response = await adminShopApi.checkShopCode(createForm.code)
    if (response.data.data) {
      ElMessage.warning('该店铺编号已存在，请使用其他编号')
    }
  } catch (error) {
    console.error('检查店铺编号失败:', error)
  }
}

// 创建店铺
const handleCreate = async () => {
  if (!createFormRef.value) return
  
  try {
    await createFormRef.value.validate()
    createLoading.value = true
    
    await adminShopApi.createShop(createForm)
    ElMessage.success('店铺创建成功')
    
    showCreateDialog.value = false
    resetCreateForm()
    await loadShops()
    
  } catch (error) {
    console.error('创建店铺失败:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    createLoading.value = false
  }
}

// 重置创建表单
const resetCreateForm = () => {
  Object.assign(createForm, {
    name: '',
    code: '',
    description: '',
    contactPhone: ''
  })
  createFormRef.value?.resetFields()
}

// 编辑店铺
const handleEdit = (shop: Shop) => {
  currentShop.value = shop
  Object.assign(editForm, {
    id: shop.id,
    name: shop.name,
    description: shop.description,
    contactPhone: shop.contactPhone
  })
  showEditDialog.value = true
}

// 更新店铺信息
const handleUpdate = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    updateLoading.value = true
    
    await adminShopApi.updateShop(editForm)
    ElMessage.success('店铺信息更新成功')
    
    showEditDialog.value = false
    await loadShops()
    
  } catch (error) {
    console.error('更新店铺失败:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message)
    }
  } finally {
    updateLoading.value = false
  }
}

// 状态变更
const handleStatusChange = async (shop: Shop, newStatus: string) => {
  try {
    await ElMessageBox.confirm(
      `确认将店铺"${shop.name}"状态变更为${getStatusName(newStatus)}吗？`,
      '确认操作',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await adminShopApi.updateShopStatus(shop.id, newStatus as any)
    ElMessage.success('店铺状态更新成功')
    await loadShops()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新店铺状态失败:', error)
      ElMessage.error('状态更新失败')
    }
  }
}

// 删除店铺
const handleDelete = async (shop: Shop) => {
  try {
    await ElMessageBox.confirm(
      `确认删除店铺"${shop.name}"吗？此操作会永久删除店铺及其所有相关数据，无法恢复！`,
      '危险操作',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'error',
        buttonSize: 'default'
      }
    )
    
    await adminShopApi.deleteShop(shop.id)
    ElMessage.success('店铺删除成功')
    await loadShops()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除店铺失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    'active': 'success',
    'suspended': 'warning',
    'closed': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态名称
const getStatusName = (status: string) => {
  const names: Record<string, string> = {
    'active': '运营中',
    'suspended': '已暂停',
    'closed': '已关闭'
  }
  return names[status] || '未知'
}

// 格式化时间
const formatTime = (timeStr: string) => {
  if (!timeStr) return '-'
  return new Date(timeStr).toLocaleString('zh-CN')
}

// 导航到首页
const navigateToHome = () => {
  router.push('/admin/dashboard')
}

// 页面加载
onMounted(() => {
  loadShops()
})
</script>

<style scoped lang="scss">
.shop-management {
  padding: 20px;
  
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 24px;
    padding: 16px 24px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .back-btn {
        border-radius: 8px;
        
        &:hover {
          transform: translateY(-1px);
        }
      }
      
      .page-info {
        h2 {
          margin: 0 0 4px 0;
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
    
    .header-right {
      .breadcrumb-link {
        cursor: pointer;
        color: #409eff;
        
        &:hover {
          color: #66b1ff;
        }
      }
    }
  }
  
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
    .toolbar-right {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
  
  .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

.el-table {
  margin-bottom: 20px;
}

.el-dialog {
  .el-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}
</style>